package com.haojin.spring;


import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @author .29.
 * @create 2023-03-01 11:00
 */
//validator接口方式实现 校验
public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return Person.class.equals(aClass);   //比对实体类的类对象与参数是否一致
    }

    @Override
    public void validate(Object o, Errors errors) { //重写校验方法
        //设置name为空时，报错：name.empty
        ValidationUtils.rejectIfEmpty(errors,"name","name.empty");

        //传入对象，强转为实体类Person对象
        Person p = (Person)o;
        if(p.getAge() < 0){     //设置age属性小于零时报错
            errors.rejectValue("age","error (age  < 0)");
        }else if(p.getAge() > 110){//设置age属性大于110报错
            errors.rejectValue("age","error (age  > 110) too old !!");
        }
    }
}
